package cc.smarnet.caihou.phone.deliver;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import cc.smarnet.caihou.IPConfig;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.adapter.DeliverAdapter;
import cc.smarnet.caihou.adapter.SpacesItemDecoration;

import cc.smarnet.caihou.entity.Deliver;
import cc.smarnet.caihou.phone.MainPageActivity;
import cc.smarnet.caihou.phone.bracts.BractsActivity;
import okhttp3.Call;

/**
* 出库信息的activity
* */
public class DeliverActivity extends AppCompatActivity {
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private LinearLayout failLoadLinearLayout;
    private LinearLayout noDataLinearLayout;
    private ProgressBar progressBar;
    private ImageButton imageButton;
    private Button addButton;

    private String token;

    private int pageNo = 1;// 取数分页的开始页
    private int pageSize = 4;// 每次取数的数量

    List<Deliver> deliverList = new ArrayList<>();
    DeliverAdapter deliverAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        noDataLinearLayout.setVisibility(View.GONE);// 隐藏暂无数据的信息
        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息

        getToken();
        getDeliverInfo();
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliverActivity.this, MainPageActivity.class);
                startActivity(intent);
            }
        });
        // 点击新增按钮的监听
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliverActivity.this, DeliverAddActivity.class);
                startActivity(intent);
            }
        });
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局(参数是：上下文、列表方向（横向还是纵向）、是否倒叙)
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new SpacesItemDecoration(20));// 设置item的上下左右边距
        recyclerView.setHasFixedSize(true);
        // 这里使用适配器的目的在于使系统不再报‘E/RecyclerView: No adapter attached; skipping layout’的错误
        /*List<deliver> nullList=new ArrayList<>();
        deliverAdapter=new deliverAdapter(nullList);
        recyclerView.setAdapter(deliverAdapter);*/

        // 下拉刷新，目前在此就不做业务处理了，因为初始时加载的那几条数据就是从第一条开始的查询的
        refreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
            }
        });

        //上拉加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {
                getDeliverInfo();
                refreshlayout.finishLoadMore(0);
            }
        });
    }

    public void initViews() {
        refreshLayout = findViewById(R.id.deliver_refreshLayout);
        recyclerView = findViewById(R.id.deliver_recyclerView);
        failLoadLinearLayout = findViewById(R.id.deliver_failLoad_linearLayout);
        noDataLinearLayout = findViewById(R.id.deliver_noData_linearLayout);
        progressBar = findViewById(R.id.deliver_progressBar);
        imageButton = findViewById(R.id.deliver_return);
        addButton = findViewById(R.id.deliver_add_button);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    public void getDeliverInfo() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/flowerOutorder/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("pageNo", String.valueOf(pageNo))
                .addParams("pageSize", String.valueOf(pageSize))
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.VISIBLE);// 显示数据加载失败的信息
                    }

                    @Override
                    public void onResponse(String response, int ID) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            String records = JSON.parseObject(result).getString("records");
                            JSONArray jsonArray = JSON.parseArray(records);
                            // 获取入库信息并存到deliverList中
                            for (int i = 0; i < jsonArray.size(); i++) {
                                String id = "";
                                String carDerver=""; // 司机
                                String carNo=""; // 车牌
                                String number=""; // 出库数量
                                String orderNo=""; // 订单号
                                int state=-2; // 状态（-1待出库,0已出库，1删除，2撤销）
                                String stateString="";// 状态的字符串
                                String stockInTime=""; // 出库时间
                                String stockOutUser=""; // 出库人
                                String remarks=""; // 备注

                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                if (jsonObj.containsKey("id")) {
                                    id = jsonObj.getString("id");
                                }
                                if (jsonObj.containsKey("carDerver")) {
                                    carDerver = jsonObj.getString("carDerver");
                                }
                                if (jsonObj.containsKey("carNo")) {
                                    carNo = jsonObj.getString("carNo");
                                }
                                if (jsonObj.containsKey("number")) {
                                    number = jsonObj.getString("number");
                                }
                                if (jsonObj.containsKey("orderNo")) {
                                    orderNo = jsonObj.getString("orderNo");
                                }
                                if (jsonObj.containsKey("state")) {
                                    state = jsonObj.getInteger("state");
                                }
                                if (jsonObj.containsKey("stockInTime")) {
                                    stockInTime = jsonObj.getString("stockInTime");
                                }
                                if (jsonObj.containsKey("stockOutUser")) {
                                    stockOutUser = jsonObj.getString("stockOutUser");
                                }
                                if (jsonObj.containsKey("remarks")) {
                                    remarks = jsonObj.getString("remarks");
                                }

                                // 设置状态值
                                switch (state){
                                    case -1:
                                        stateString="待出库";
                                        break;
                                    case 0:
                                        stateString="已出库";
                                        break;
                                    case 1:
                                        stateString="删除";
                                        break;
                                    case 2:
                                        stateString="撤销";
                                        break;
                                    default:
                                        stateString="未知";
                                }

                                Deliver deliver = new Deliver();
                                deliver.setId(id);
                                deliver.setCarDerver(carDerver);
                                deliver.setCarNo(carNo);
                                deliver.setNumber(number);
                                deliver.setOrderNo(orderNo);
                                deliver.setState(state);
                                deliver.setStateSting(stateString);
                                deliver.setStockInTime(stockInTime);
                                deliver.setStockOutUser(stockOutUser);
                                deliver.setRemarks(remarks);

                                deliverList.add(deliver);
                            }
                            if (deliverList.size() > 0) {// 如果deliverList中有数据的话就通过deliverAdapter将数据显示在界面上
                                deliverAdapter = new DeliverAdapter(getApplicationContext(),deliverList);
                                recyclerView.setAdapter(deliverAdapter);
                            }else {// 否则让暂无数据的信息显示在界面上
                                noDataLinearLayout.setVisibility(View.VISIBLE);
                            }

                            int total=Integer.valueOf(JSON.parseObject(result).getString("total"));//数据在数据库中的总数
                            int current=Integer.valueOf(JSON.parseObject(result).getString("current"));//该次取数是第几次
                            if (current*pageSize>=total){
                                Toast.makeText(DeliverActivity.this, "已加载完所有数据", Toast.LENGTH_SHORT).show();
                            }

                            pageNo += 1;
                        }
                    }
                });
    }
}